<template>
  <div>
    <!-- Methodology界面 -->
    <div :class="{hidden: isHidden}">
      <div class="app-container">
        <!-- 搜索面板 -->
        <el-row>
          <search-panel
            search
            :create="canCreate"
            methodology
            :item-name="$t('n')+$t('Methodology')"
            :item-number="totalNum"
            @on-search="onSearch"
            @on-create="onCreate"
          />
        </el-row>
        <!-- 数据列表 -->
        <el-row>
          <el-table
            loading="listLoading"
            :data="list"
            :stripe="true"
            element-loading-text="Loading"
            :border="false"
            :header-cell-style="{color:'black'}"
            fit
            highlight-current-row
          >
            <!-- <el-table v-loading="listLoading" :data="this.$store.state.slist" :stripe="true" element-loading-text="Loading" :border="false" :header-cell-style="{color:'black'}" fit highlight-current-row> -->
            <!-- 第一列 名称 -->
            <el-table-column :label="$t('name')" align="center" min-width="14%">
              <template v-slot="scope">
                {{ scope.row.name }}
              </template>
            </el-table-column>
            <!-- 第二列 内容 -->
            <el-table-column :label="$t('content')" align="center" min-width="33%">
              <template v-slot="scope">
                <!-- tips悬浮提示 -->
                <el-tooltip
                  v-model="scope.row.showTooltip"
                  placement="top"
                  :open-delay="500"
                  effect="dark"
                  :disabled="!scope.row.showTooltip"
                >
                  <!--                  <div slot="content">{{ scope.row.content}}</div>-->
                  <div class="myNote" @mouseenter="showTips($event,scope.row)">{{ scope.row.content }}</div>
                </el-tooltip>
                <!--                {{ scope.row.content }}-->
              </template>
            </el-table-column>
            <!-- 第三列 操作 -->
            <el-table-column align="center" :label="$t('operation')" width="119px" fixed="right">
              <template v-slot="scope">
                <div
                  v-if="$store.getters.isAdmin()"
                  style="display:inline-block; margin-right: 5px;"
                >
                  <a class="font-blue" @click="toEdit(scope.row.id, scope.$index)">{{ $t('edit') }}</a>
                </div>
                <div
                  v-if="$store.getters.isAdmin()"
                  style="display:inline-block"
                >
                  <a class="font-blue" @click="toDelete(scope.row.id)">{{ $t('delete') }}</a>
                </div>
                <div>
                  <a class="font-blue" @click="toDetail(scope.row.id, scope.$index)">{{ $t('detail') }}</a>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-row>

        <!-- 页数-->
        <el-row>
          <el-pagination
            align="center"
            :current-page="currentPage"
            :page-size="pageSize"
            :page-count="pageNum"
            @current-change="freshList"
          />
        </el-row>
      </div>
    </div>

    <div :class="{hidden: !isHidden}">
      <router-view />
    </div>
  </div>
</template>

<script>
import { getMethodologies, deleteMethodologies, retrieveMethodologies, searchMethodologies } from '@/api/methodology.js'

import SearchPanel from '@/components/SearchPanel/index.vue'
import store from '@/store'

export default {
  components: {
    SearchPanel
  },
  data() {
    return {
      // 查询
      searchForm: {
        key: ''
      },
      list: [],
      listLoading: true,
      pageSize: 15,
      totalNum: 0,
      pageNum: 0,
      currentPage: 1,
      hidden: true,

      // 用于三极路由
      isHidden: false
    }
  },
  computed: {
    store() {
      return store
    },
    canCreate() {
      return this.$store.getters.isAdmin()
    }
  },
  created() {
    if (this.$route.path !== '/methodology/index') {
      this.isHidden = true
    } else {
      this.freshList(1)
      this.listLoading = false
    }
  },
  methods: {
    showTips(obj, row) {
      /* obj为鼠标移入时的事件对象*/
      /* currentWidth 为文本在页面中所占的宽度，创建标签，加入到页面，获取currentWidth ,最后在移除*/
      const TemporaryTag = document.createElement('span')
      TemporaryTag.innerText = row.note
      TemporaryTag.className = 'getTextWidth'
      document.querySelector('body').appendChild(TemporaryTag)

      const currentWidth = document.querySelector('.getTextWidth').offsetWidth

      document.querySelector('.getTextWidth').remove()

      /* cellWidth为表格容器的宽度*/

      const cellWidth = obj.target.offsetWidth

      /* 当文本宽度小于||等于容器宽度两倍时，代表文本显示未超过两行*/

      currentWidth <= (4 * cellWidth) ? row.showTooltip = false : row.showTooltip = true
    },
    // stateFormat(row, column, cellValue) {
    //   console.log('--------------------statteformat--------------------')
    //   // 检查cellValue是否为空
    //   if (!cellValue) return ''
    //
    //   // 创建一个临时的div来测量文本的高度
    //   const tempDiv = document.createElement('div')
    //   tempDiv.style.width = '100%' // 假设这个宽度与el-table-column的宽度一致
    //   tempDiv.style.visibility = 'hidden'
    //   tempDiv.style.position = 'absolute'
    //   tempDiv.style.whiteSpace = 'normal' // 允许文本换行
    //   document.body.appendChild(tempDiv)
    //
    //   // 设置临时div的文本内容
    //   tempDiv.textContent = cellValue
    //
    //   // 计算临时div的行数
    //   const lineHeight = parseFloat(window.getComputedStyle(tempDiv).lineHeight)
    //   const height = tempDiv.offsetHeight
    //   const maxLines = 4 // 最大行数
    //   const estimatedLines = height / lineHeight
    //
    //   // 如果超过最大行数，则截断文本
    //   if (estimatedLines > maxLines) {
    //     // 计算截断后的文本高度
    //     const truncatedHeight = lineHeight * maxLines
    //     let truncatedValue = ''
    //     const words = cellValue.split(' ')
    //     let currentHeight = 0
    //
    //     for (let i = 0; i < words.length; i++) {
    //       tempDiv.textContent = truncatedValue + words[i] + ' '
    //       currentHeight = tempDiv.offsetHeight
    //       if (currentHeight <= truncatedHeight) {
    //         truncatedValue += words[i] + ' '
    //       } else {
    //         // 移除最后一个添加的词，因为它导致超出高度限制
    //         tempDiv.textContent = truncatedValue.trim()
    //         break
    //       }
    //     }
    //
    //     // 添加省略号
    //     truncatedValue = truncatedValue.trim() + '...'
    //
    //     // 移除临时div
    //     document.body.removeChild(tempDiv)
    //     return truncatedValue
    //   }
    //
    //   // 如果没有超过最大行数，返回原始文本
    //   document.body.removeChild(tempDiv)
    //   return cellValue
    // },
    retrieveMethodologies() {
      let retrieve = {
        'instruction': 'string',
        'topk': 100
      }
      retrieve = JSON.stringify(retrieve)
      // console.log(insturction)
      retrieveMethodologies(retrieve).then(response => {
        console.log(response.data)
        // this.$message({
        //   message: '检索成功',
        //   type: 'success'
        // })
      }).catch(error => {
        console.log(error)
        this.$message({
          message: this.$t('Retrieval_failed'),
          type: 'error'
        })
      }
      )
    },

    // 更新列表
    freshList(nowPage) {
      this.listLoading = true
      this.currentPage = nowPage
      let number = {
        'page': this.currentPage,
        'pagesize': this.pageSize
      }
      number = JSON.stringify(number)
      // console.log(insturction)
      getMethodologies(number).then(response => {
        const data = response
        this.totalNum = data.total_methodologies
        this.list = data.methodologies
        this.pageNum = Math.ceil(this.totalNum / this.pageSize) // 计算总页数
        // this.$message({
        //   message: '获取成功',
        //   type: 'success'
        // })
      }).catch(error => {
        console.log(error)
        this.$message({
          message: this.$t('acquisition_failure'),
          type: 'error'
        })
      })
    },
    // 跳转到详情页面
    toDetail(id, index) {
      this.$router.push({
        path: '/methodology/index/detail',
        query: {
          id: id,
          name: this.list[index].name,
          content: this.list[index].content,
          content_json: this.list[index].content_json,
        }
      })
    },
    // 编辑页面
    toEdit(id, index) {
      // console.log(this.list[index].name, this.list[index].content)
      this.$router.push({
        path: '/methodology/index/detail/edit',
        query: {
          id: id,
          name: this.list[index].name,
          content: this.list[index].content,
          content_json: this.list[index].content_json
        }
      })
    },
    // 删除
    toDelete(id) {
      this.$confirm(this.$t('methodology_delete_tips'), this.$t('tip'), {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        type: 'warning',
        closeOnClickModal: false
      }).then(() => {
        // 删除该Methodology
        deleteMethodologies(id).then(response => {
          console.log(response.data)
          // 刷新页面
          this.freshList(1)
          this.$message({
            message: this.$t('delete_success_tips'),
            type: 'success'
          })
        }).catch(error => {
          console.log(error)
          this.$message({
            message: this.$t('delete_error_tips'),
            type: 'error'
          })
        })
      }).catch(error => {
        console.log(error)
        this.$message({
          message: this.$t('delete_cancel_tips'),
          type: 'info'
        })
      })
    },
    // 搜索
    onSearch(key) {
      // this.searchForm.key = key
      // this.freshList(1)

      let searchValue = {
        'search': key
      }
      searchValue = JSON.stringify(searchValue)
      searchMethodologies(searchValue).then(response => {
        // console.log(response)
        const data = response
        this.totalNum = data ? data.length : 0
        console.log(data)
        this.list = data
        // this.$message({
        //   message: '获取成功',
        //   type: 'success'
        // })
      }).catch(error => {
        console.log(error)
        this.$message({
          message: this.$t('acquisition_failure'),
          type: 'error'
        })
      })
    },
    // 新建
    onCreate() {
      this.$router.push({ path: '/methodology/index/create' })
    }

  }
}
</script>

<style>
/*.app-container{*/
/*!*  !*position: center;*!*!*/
/*!*  !*position: absolute;*!*!*/
/*!*  !*left: 5%;*!*!*/
/*  width: 90%;*/
/*}*/
.app-container{
  padding: 20px;
}
.font-blue {
  color: #66b1ff
}
.hidden{
  display: none;
}
/*.el-tooltip__popper{*/
/*  max-width:20%;*/
/*}*/
/*.el-tooltip__popper,.el-tooltip__popper.is-dark{*/
/*  background: rgb(247, 249, 252) !important;*/
/*  color: #070707 !important;*/
/*  line-height: 24px;*/
/*}*/
.myNote{

  display:-webkit-box;

  text-overflow:ellipsis;

  overflow:hidden;

  -webkit-line-clamp: 4;

  -webkit-box-orient:vertical;

}
</style>
